package com.weixin.interceptor;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.frame.ar.util.TimeUtil;
import com.frame.util.StringUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.weixin.model.AppUser;
import com.weixin.service.WxWyPublicService;

public class WeiXinLoinInterceptor implements Interceptor {

	@Override
	public void intercept(ActionInvocation ai) {
		// 全局处理器处理
		Controller c = ai.getController();
		// 绑定微信账号
		Object appUser = c.getSession().getAttribute("appUser");
		/*取消验证
		if(1==1){
			ai.invoke();
			return;
		}*/
		
		if(appUser==null){
			//用户未登录，如果用户已经绑定则从微信的授权code获取用户信息与后台匹配并信息自动登录，否则跳转到bind界面
			//获取微信授权登录信息
			String code = c.getPara("code");
			String state = c.getPara("state");
			if(StrKit.isBlank(code)||!WxWyPublicService.validateState(state)){
				
//				c.renderError(404);
//				return;
				//TODO 测试代码
				//使用默认账号登录
				String openId = "oJiOFxPPoIFpwb49XFdvf1gZhJsM";
				appUser = AppUser.dao.getBindUserByOpenId(openId);
				c.setSessionAttr("appUser", appUser);
				AppUser.setCurrentUser(appUser);
				ai.invoke();
				return;
			}
			//根据微信授权code获取绑定的用户信息
			appUser = WxWyPublicService.getAppUserByCode(code);
			
			if(appUser==null){
				c.renderError(500);
				return;
			}
			AppUser au = (AppUser) appUser;
			Integer bindStatus = au.getInt("bindStatus");
			
			if(bindStatus==0){
				//跳转到bind界面
				//c.setSessionAttr("appUser", appUser);
				//内部转发
				//c.redirect("/wxwyapp/user/toBindWeiXin");
				//设置重定向地址
				c.setAttr("redirectUrl",  c.getSessionAttr("requestURI"));
				//设置用户openId
				c.setAttr("openId", au.getStr("openId"));
				c.forwardAction("/wxwyapp/user/toBindWeiXin");
			}else{
				//设置session对象，完成自动登录
				c.setSessionAttr("appUser", appUser);
				AppUser.setCurrentUser(appUser);
				//设置用户登录token
				String token = UUID.randomUUID().toString();
				au.set("loginToken", token);
				au.set("loginTime",TimeUtil.newTimestamp());
				au.update();
				//TODO 根据用户类型跳转到对应的界面
				ai.invoke();
			}
		}else{
			
			ai.invoke();
		}
		
	}

}
